package com.atguigu.product.products.service.impl;

import com.atguigu.product.products.dao.PmsBrandDao;
import com.atguigu.product.products.dao.PmsCategoryDao;
import com.atguigu.product.products.entity.PmsBrandEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.product.products.dao.PmsCategoryBrandRelationDao;
import com.atguigu.product.products.entity.PmsCategoryBrandRelationEntity;
import com.atguigu.product.products.service.PmsCategoryBrandRelationService;


@Service("pmsCategoryBrandRelationService")
public class PmsCategoryBrandRelationServiceImpl extends ServiceImpl<PmsCategoryBrandRelationDao, PmsCategoryBrandRelationEntity> implements PmsCategoryBrandRelationService {
    @Autowired
    private PmsCategoryDao pmsCategoryDao;

    @Autowired
    private PmsBrandDao pmsBrandDao;

    @Autowired
    private PmsCategoryBrandRelationDao categoryBrandRelationDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PmsCategoryBrandRelationEntity> page = this.page(
                new Query<PmsCategoryBrandRelationEntity>().getPage(params),
                new QueryWrapper<PmsCategoryBrandRelationEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 新增数据到品牌分类维护表中
     *
     * @param pmsCategoryBrandRelation
     */
    public void saveDetail(PmsCategoryBrandRelationEntity pmsCategoryBrandRelation) {
        //由于需要保存品牌名称和分类名称，数据量太大不去做多表联合
        //根据品牌id查询品牌名称并赋值
        pmsCategoryBrandRelation.setBrandName(pmsBrandDao.selectById(pmsCategoryBrandRelation.getBrandId()).getName());
        //根据分类id查询分类名称并赋值
        pmsCategoryBrandRelation.setCatelogName(pmsCategoryDao.selectById(pmsCategoryBrandRelation.getCatelogId()).getName());
        //插入表
        this.save(pmsCategoryBrandRelation);
    }

    /**
     * 根据分类id查询品牌信息
     *
     * @param catId
     * @return
     */
    public List<PmsBrandEntity> brandsList(Long catId) {
        List<PmsCategoryBrandRelationEntity> categoryBrands = categoryBrandRelationDao.selectList(new QueryWrapper<PmsCategoryBrandRelationEntity>().eq("catelog_id", catId));
        if (categoryBrands != null && categoryBrands.size() > 0) {
            List<Long> longIds = categoryBrands.stream().map(m -> m.getBrandId()).collect(Collectors.toList());
            //查询所属品牌信息
            List<PmsBrandEntity> pmsBrandEntities = pmsBrandDao.selectList(new QueryWrapper<PmsBrandEntity>().in("brand_id", longIds));
            return pmsBrandEntities;
        }
        return null;
    }

}